import { defineStore } from 'pinia'
import { ref } from 'vue'
import { DEFAULT_AVATAR } from '@/assets/img/default-avatar'

const useUserStore = defineStore('user', () => {
    // 用户信息
    const token = ref(localStorage.getItem('token') || '')
    const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))

    // 登录
    function login(username, password) {
        return new Promise((resolve) => {
            // 模拟接口调用
            setTimeout(() => {
                // 模拟获取token和用户信息
                const mockToken = 'mock_token_' + Date.now()

                // 从本地存储获取已注册的用户信息
                const registeredUsers = JSON.parse(localStorage.getItem('registeredUsers') || '[]')
                const user = registeredUsers.find(user => user.username === username && user.password === password)

                if (user) {
                    // 登录成功，不保存密码到状态中
                    const { password, ...userWithoutPassword } = user

                    // 保存到store
                    token.value = mockToken
                    userInfo.value = userWithoutPassword

                    // 保存到本地存储
                    localStorage.setItem('token', mockToken)
                    localStorage.setItem('userInfo', JSON.stringify(userWithoutPassword))

                    resolve({ success: true, token: mockToken, userInfo: userWithoutPassword })
                } else {
                    // 登录失败
                    resolve({ success: false, message: '用户名或密码错误' })
                }
            }, 500)
        })
    }

    // 注册
    function register(userData) {
        return new Promise((resolve) => {
            // 模拟注册接口
            setTimeout(() => {
                try {
                    // 添加默认头像和用户ID
                    const newUser = {
                        ...userData,
                        userId: 'user_' + Date.now(),
                        avatar: DEFAULT_AVATAR,
                        signature: userData.signature || '这个人很懒，什么都没留下'
                    }

                    // 获取已注册用户列表
                    const registeredUsers = JSON.parse(localStorage.getItem('registeredUsers') || '[]')

                    // 检查用户名是否已存在
                    if (registeredUsers.some(user => user.username === userData.username)) {
                        resolve({ success: false, message: '用户名已存在' })
                        return
                    }

                    // 添加新用户到列表
                    registeredUsers.push(newUser)
                    localStorage.setItem('registeredUsers', JSON.stringify(registeredUsers))

                    resolve({ success: true, message: '注册成功' })
                } catch (error) {
                    console.error('注册错误:', error)
                    resolve({ success: false, message: '注册失败' })
                }
            }, 500)
        })
    }

    // 退出登录
    function logout() {
        token.value = ''
        userInfo.value = {}
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
    }

    // 更新用户信息
    function updateUserInfo(newUserInfo) {
        return new Promise((resolve) => {
            setTimeout(() => {
                try {
                    // 更新状态
                    userInfo.value = { ...userInfo.value, ...newUserInfo }

                    // 更新本地存储
                    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))

                    // 同步更新已注册用户列表中的信息
                    const registeredUsers = JSON.parse(localStorage.getItem('registeredUsers') || '[]')
                    const updatedUsers = registeredUsers.map(user => {
                        if (user.userId === userInfo.value.userId) {
                            return { ...user, ...newUserInfo }
                        }
                        return user
                    })
                    localStorage.setItem('registeredUsers', JSON.stringify(updatedUsers))

                    resolve({ success: true, message: '更新成功' })
                } catch (error) {
                    console.error('更新用户信息错误:', error)
                    resolve({ success: false, message: '更新失败' })
                }
            }, 500)
        })
    }

    // 更新头像
    function updateAvatar(avatarUrl) {
        return updateUserInfo({ avatar: avatarUrl })
    }

    // 判断是否已登录
    const isLoggedIn = () => !!token.value

    return {
        token,
        userInfo,
        login,
        register,
        logout,
        isLoggedIn,
        updateUserInfo,
        updateAvatar
    }
})

export default useUserStore 